<template>
  <el-dialog
    v-bind="$attrs"
    :title="$t('page.import')"
    width="500px"
    @open="handleOpen()"
    @close="handleClose"
    @closed="() => (step = 0)"
  >
    <!-- <el-steps
      :space="200"
      :active="step"
      simple
      class="mb-3 justify-center items-center"
      finish-status="success"
    >
      <el-step :title="$t('common.config')"></el-step>
      <el-step :title="$t('common.push')"></el-step>
      <el-step :title="$t('common.end')"></el-step>
    </el-steps>-->
    <!-- step 1 -->
    <div
      class="flex justify-center cursor-pointer m-auto w-pushapp-card"
    >
      <div class="flex items-center">
        <img
          src="@/assets/images/logo/ota.png"
          alt
          width="60"
          height="60"
          class="mr-12"
        />
          <el-form
            @submit.prevent.native
            ref="selectFirm"
            :model="firmForm"
            :rules="rules"
            label-position="top"
          >
            <el-form-item
              prop="modelCode"
              :label="$t('device.modelCode') + ':'"
            >
              <el-select
                v-model="firmForm.modelCode"
                class="w-full"
                :placeholder="$t('device.modelCode')"
                @change="getFirmVersions"
              >
                <el-option
                  v-for="devModel in this.deviceModels"
                  :key="devModel.modelCode + devModel.deviceFlag"
                  :label="
                    devModel.modelCode +
                    (devModel.deviceFlag
                      ? ' (' + devModel.deviceFlag + ')'
                      : '')
                  "
                  :value="
                    devModel.modelCode +
                    (devModel.deviceFlag ? '-' + devModel.deviceFlag : '')
                  "
                />
              </el-select>
            </el-form-item>
            <el-form-item
              prop="currentVersion"
              :label="$t('batch.version') + ':'"
            >
              <el-select
                v-model="firmForm.currentVersion"
                class="w-full"
                :placeholder="$t('batch.version')"
              >
                <el-option
                  v-for="item in firmVersions"
                  :key="item.versionName"
                  :label="item.versionName"
                  :value="item.versionName"
                />
              </el-select>
            </el-form-item>
          </el-form>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button text @click="handleClose">{{
          $t('common.cancel')
        }}</el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="pushApp"
          v-show="step === 0"
          >{{ $t('common.confirm') }}</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { queryVersionList } from '@/api/sysapp'
import { addBatchDeviceByApp } from '@/api/batch'
import { getModelAndDeviceFlagList } from '@/api/batch'

export default {
  inheritAttrs: false,
  props: { batchId: String },
  data() {
    return {
      step: 0,
      total: 100,
      modelName: '',
      deviceFlag: '',
      modelCode: '',
      manufacturerCode: '',
      deviceModels: [],
      firmVersions: [],
      firmForm: {
        modelCode: '',
        currentVersion: ''
      },
      loading: false,
      pushSuccess: false,
      devSn: ''
    }
  },
  computed: {
    rules() {
      return {
        modelCode: [
          {
            required: true,
            message: this.$t('batch.please_select_firm_model'),
            trigger: 'blur'
          }
        ],
        currentVersion: [
          {
            required: true,
            message: this.$t('batch.please_select_firm_verison'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    devRes(value) {
      if (value) {
        if (value.baseInfo) {
          this.modelName = value.baseInfo.modelName
          this.modelCode = value.baseInfo.modelCode
          this.deviceFlag = value.baseInfo.deviceFlag
          this.manufacturerCode = value.baseInfo.manufacturerCode
        }
        this.devSn = value.deviceBind.devSn
      }
    }
  },
  mounted() {},
  methods: {
    handleClose() {
      this.$refs['selectFirm'].resetFields()
      this.$emit('update:model-value', false)
    },
    handleOpen() {
      this.getDeviceModel()
    },
    getDeviceModel() {
      getModelAndDeviceFlagList({}).then((res) => {
        this.deviceModels = res
        console.log(this.deviceModels)
        if (this.deviceModels.length > 0) {
          this.firmForm.modelCode = this.deviceModels[0].modelCode
          // this.getFirmVersions()
          this.getFirmVersions(
            this.deviceModels[0].modelCode +
              (this.deviceModels[0].deviceFlag
                ? '-' + this.deviceModels[0].deviceFlag
                : '')
          )
        }
      })
    },
    getFirmVersions(value) {
      if (value != '') {
        let deviceModel = value.split('-')[0]
        let deviceFlag = value.split('-')[1]
        queryVersionList({
          appTypeCode: '01',
          modelCode: deviceModel,
          deviceFlag: deviceFlag
        }).then((res) => {
          this.firmVersions = res
          this.firmForm.currentVersion = ''
        })
      } else {
        this.firmVersions = []
      }
    },
    pushApp() {
      this.$refs['selectFirm'].validate((valid) => {
        if (valid) {
          this.loading = true
          let deviceModel
          let deviceFlag
          if (this.firmForm.modelCode != '') {
            deviceModel = this.firmForm.modelCode.split('-')[0]
            deviceFlag = this.firmForm.modelCode.split('-')[1]
          }
          addBatchDeviceByApp(this.batchId, {
            versionName: this.firmForm.currentVersion,
            modelCode: deviceModel,
            deviceFlag: deviceFlag,
            appTypeCode: '01'
          })
            .then(() => {
              this.$message.success(this.$t('batch.tip_firmware_add_success'))
              this.$emit('refreshDataList')
              this.handleClose()
              this.loading = false
            })
            .catch((e) => {
              this.$confirmError(e)
              this.loading = false
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>

<style>
::v-deep .el-dialog .el-dialog__body {
  padding: 0;
}
</style>
